package org.xiaoxiao.dao;

import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import org.xiaoxiao.pojo.AdminAccount;
import org.xiaoxiao.pojo.Book;
import org.xiaoxiao.pojo.VoteRecord;
import org.xiaoxiao.pojo.VoteSystemData;

import java.io.File;
import java.util.*;

public class BookVoteDao {
    private static final String XML_FILE = "vote-data.xml";
    private final XmlMapper xmlMapper = new XmlMapper();

    public BookVoteDao() {
        // 初始化数据文件（如果不存在）
        if (!new File(XML_FILE).exists()) {
            System.out.println("初始化数据文件...");
            saveData(createInitialData());
        }
    }

    // 主数据操作方法
    private VoteSystemData loadData() {
        try {
            return xmlMapper.readValue(new File(XML_FILE), VoteSystemData.class);
        } catch (Exception e) {
            System.err.println("加载数据失败: " + e.getMessage());
            return null;
        }
    }

    private void saveData(VoteSystemData data) {
        try {
            xmlMapper.writerWithDefaultPrettyPrinter()
                    .writeValue(new File(XML_FILE), data);
        } catch (Exception e) {
            System.err.println("保存数据失败: " + e.getMessage());
        }
    }

    // 核心业务方法
    public List<Book> getAllBooks() {
        VoteSystemData data = loadData();
        return data != null ? data.getBooks() : Collections.emptyList();
    }

    public boolean hasVoted(String ip) {
        VoteSystemData data = loadData();
        if (data == null) return false;

        return data.getVoteRecords().stream()
                .anyMatch(record -> ip.equals(record.getIp()));
    }

    public void addVote(String bookId, String ip) {
        VoteSystemData data = loadData();
        if (data == null) return;

        // 更新书籍票数
        data.getBooks().stream()
                .filter(book -> bookId.equals(book.getId()))
                .findFirst()
                .ifPresent(book -> book.setVotes(book.getVotes() + 1));

        // 添加投票记录
        VoteRecord record = new VoteRecord();
        record.setIp(ip);
        record.setBookId(bookId);
        data.getVoteRecords().add(record);

        saveData(data);
    }

    public boolean isValidAdmin(String username, String password) {
        VoteSystemData data = loadData();
        return data != null &&
                username.equals(data.getAdmin().getUsername()) &&
                password.equals(data.getAdmin().getPassword());
    }

    // 管理员操作
    public boolean addBook(Book newBook) {
        VoteSystemData data = loadData();
        if (data == null) return false;

        // 检查ID是否唯一
        boolean idExists = data.getBooks().stream()
                .anyMatch(book -> book.getId().equals(newBook.getId()));

        if (idExists) {
            System.err.println("添加书籍失败: ID已存在");
            return false;
        }

        data.getBooks().add(newBook);
        saveData(data);
        return true;
    }

    public boolean updateBook(String bookId, String title, String author) {
        VoteSystemData data = loadData();
        if (data == null) return false;

        boolean updated = data.getBooks().stream()
                .filter(book -> bookId.equals(book.getId()))
                .findFirst()
                .map(book -> {
                     book.setTitle(title);
                     book.setAuthor(author);
                     return true;
                 })
                .orElse(false);

        if (updated) {
            saveData(data);
        }

        return updated;
    }

    public boolean deleteBook(String bookId) {
        VoteSystemData data = loadData();
        if (data == null) return false;

        boolean removed = data.getBooks().removeIf(book -> bookId.equals(book.getId()));

        if (removed) {
            // 删除相关投票记录
            data.getVoteRecords().removeIf(record -> bookId.equals(record.getBookId()));
            saveData(data);
        }

        return removed;
    }

    // 初始化数据
    private VoteSystemData createInitialData() {
        VoteSystemData data = new VoteSystemData();

        // 初始化管理员
        AdminAccount admin = new AdminAccount();
        admin.setUsername("admin");
        admin.setPassword("123");
        data.setAdmin(admin);

        // 初始化书籍列表
        List<Book> books = new ArrayList<>();
        books.add(createBook("1", "第二次机器革命", "埃里克•布莱恩约弗森", 33));
        books.add(createBook("2", "千脑智能", "杰夫·霍金斯", 21));
        books.add(createBook("3", "深度学习革命", "凯德•梅茨", 18));
        books.add(createBook("4", "生命3.0", "迈克斯·泰格马克", 14));
        data.setBooks(books);

        // 初始投票记录
        data.setVoteRecords(new ArrayList<>());

        return data;
    }

    private Book createBook(String id, String title, String author, int votes) {
        Book book = new Book();
        book.setId(id);
        book.setTitle(title);
        book.setAuthor(author);
        book.setVotes(votes);
        return book;
    }

    // 管理员专用：获取所有投票记录
    public List<VoteRecord> getAllVoteRecords() {
        VoteSystemData data = loadData();
        return data != null ? data.getVoteRecords() : Collections.emptyList();
    }
}